package afeng.world.pangu;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @datetime: 2020/8/7 21:32
 * @project_name: pangu
 * @author: afeng
 */
public class CglibDemo {

    /**
     *  1.classloader 创建代理Class对象
     *  2.interface 定义相同接口
     *  3. invocationHandler 实现功能类
     *
     *  Proxy.newProxyInstance(classloader, interfaces, invocationHandler)
     *
     *  Enhancer.setClassLoader()
     *  Enhancer.setSuperClass()
     *  Enhancer.setCallBack() --> MethodInterceptor (cglib)
     *  Enhancer.creater()
     */
    public static void main(String arg[]){

        PressKey pressKey = new PressKey();

        MethodInterceptor methodInterceptor = new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("奇诡的知识又增加了");
                PressKey invoke = (PressKey)method.invoke(pressKey, objects);
                return invoke;
            }

        };

        Enhancer enhancer = new Enhancer();
        enhancer.setClassLoader(CglibDemo.class.getClassLoader());
        enhancer.setSuperclass(PressKey.class);
        enhancer.setCallback(methodInterceptor);
        PressKey cglibProxy = (PressKey)enhancer.create();

        System.out.println(cglibProxy.test());
    }
}
